package org.example.scoresystem_backen.service.impl;

import org.example.scoresystem_backen.dto.AdminDTO;
import org.example.scoresystem_backen.dto.PageRequest;
import org.example.scoresystem_backen.dto.PageResponse;
import org.example.scoresystem_backen.entity.Admin;
import org.example.scoresystem_backen.mapper.AdminMapper;
import org.example.scoresystem_backen.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 管理员服务实现类
 */
@Service
@Transactional
public class AdminServiceImpl implements AdminService {
    
    @Autowired
    private AdminMapper adminMapper;
    
    @Override
    public Admin login(String username, String password) {
        Admin admin = adminMapper.findByUsernameAndPassword(username, password);
        if (admin != null) {
            return admin;
        }
        throw new RuntimeException("用户名或密码错误");
    }

    @Override
    public Admin createAdmin(Admin admin) {
        // 检查用户名是否已存在
        if (adminMapper.existsByUsername(admin.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }

        adminMapper.insert(admin);
        return admin;
    }

    @Override
    public Admin updateAdmin(Admin admin) {
        // 检查管理员是否存在
        Admin existingById = adminMapper.findById(admin.getId());
        if (existingById == null) {
            throw new RuntimeException("管理员不存在");
        }

        // 检查用户名是否被其他管理员使用
        if (adminMapper.existsByUsernameExcludeId(admin.getUsername(), admin.getId())) {
            throw new RuntimeException("用户名已被其他管理员使用");
        }

        adminMapper.update(admin);
        return admin;
    }

    @Override
    public void deleteAdmin(Integer id) {
        Admin admin = adminMapper.findById(id);
        if (admin == null) {
            throw new RuntimeException("管理员不存在");
        }
        adminMapper.deleteById(id);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Admin findById(Integer id) {
        Admin admin = adminMapper.findById(id);
        if (admin != null) {
            return admin;
        }
        throw new RuntimeException("管理员不存在");
    }

    @Override
    @Transactional(readOnly = true)
    public Admin findByUsername(String username) {
        Admin admin = adminMapper.findByUsername(username);
        if (admin != null) {
            return admin;
        }
        throw new RuntimeException("管理员不存在");
    }

    @Override
    @Transactional(readOnly = true)
    public List<Admin> findAll() {
        return adminMapper.findAll();
    }

    @Override
    @Transactional(readOnly = true)
    public Page<Admin> findAll(Pageable pageable) {
        // MyBatis不直接支持分页，这里简化处理
        List<Admin> allAdmins = adminMapper.findAll();
        int start = (int) pageable.getOffset();
        int end = Math.min((start + pageable.getPageSize()), allAdmins.size());
        List<Admin> pageContent = allAdmins.subList(start, end);
        return new PageImpl<>(pageContent, pageable, allAdmins.size());
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<Admin> findByRole(Admin.Role role) {
        return adminMapper.findByRole(role);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Admin> findByUsernameContaining(String username) {
        return adminMapper.findByUsernameContaining(username);
    }

    @Override
    @Transactional(readOnly = true)
    public boolean existsByUsername(String username) {
        return adminMapper.existsByUsername(username);
    }

    @Override
    public boolean changePassword(Integer id, String oldPassword, String newPassword) {
        Admin admin = adminMapper.findById(id);
        if (admin != null) {
            if (admin.getPassword().equals(oldPassword)) {
                admin.setPassword(newPassword);
                adminMapper.update(admin);
                return true;
            } else {
                throw new RuntimeException("原密码错误");
            }
        }
        throw new RuntimeException("管理员不存在");
    }

    @Override
    @Transactional(readOnly = true)
    public PageResponse<AdminDTO> findAdminsByPage(PageRequest pageRequest) {
        pageRequest.validate();

        // 解析角色过滤条件
        Admin.Role roleFilter = null;
        if (pageRequest.getSearch() != null && pageRequest.getSearch().startsWith("role:")) {
            String roleValue = pageRequest.getSearch().substring(5);
            try {
                roleFilter = Admin.Role.fromValue(roleValue);
                pageRequest.setSearch(null); // 清除搜索条件，因为已转换为角色过滤
            } catch (IllegalArgumentException e) {
                // 忽略无效的角色值
            }
        }

        // 查询数据
        List<Admin> admins = adminMapper.findAdminsByPage(
            pageRequest.getSearch(),
            roleFilter,
            pageRequest.getOffset(),
            pageRequest.getLimit()
        );

        // 转换为DTO
        List<AdminDTO> adminDTOs = admins.stream()
            .map(AdminDTO::fromEntity)
            .collect(Collectors.toList());

        // 查询总数
        Long totalCount = adminMapper.countAdminsWithFilter(
            pageRequest.getSearch(),
            roleFilter
        );

        return PageResponse.of(pageRequest, totalCount, adminDTOs);
    }
}
